import type { RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/store/module/user'
import { admin } from '@/request/api'
import { ElMessage } from 'element-plus'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/Login.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 前置导航守卫
router.beforeEach(async (to, from, next) => {
  // token && pinia 里面 menus(权限列表) 为空
  const token = localStorage.getItem('token')
  const userStore = useUserStore()
  if (token && userStore.menus.length === 0) {
    let res = await admin.APIAdminInfo()
    if (res.code === 200) {
      if (res.data.menus.length === 0) {
        ElMessage.warning('当前账号没有权限')
        localStorage.removeItem('token')
        return next('/login')
      }
      router.addRoute({
        path: '/',
        name: 'home',
        component: () => import('@/views/home/Home.vue'),
        redirect: '/index',
        children: [
          {
            path: '/index',
            name: 'index',
            component: () => import('@/views/index/Index.vue'),
          },
        ],
      })
      // userStore.updateMenus(res.data.menus)
      userStore.menus = res.data.menus
      userStore.username = res.data.username
      const menus = userStore.getMenusRoutes
      // const newRoutes: RouteRecordRaw[] = []
      // console.log(menus)
      // 循环菜单对象
      for (const key in menus) {
        const newRoute: RouteRecordRaw = {
          path: '/' + menus[key].name,
          name: menus[key].name,
          component: () => import('@/views/home/Home.vue'),
          redirect: '/' + menus[key].name + '/' + menus[key].children![0].name,
          children: [],
        }
        menus[key].children!.forEach((item) => {
          if (!item.hidden) {
            newRoute.children!.push({
              path: item.name,
              name: item.name,
              component: () => import(`@/views/${menus[key].name}/${item.name.charAt(0).toUpperCase() + item.name.slice(1)}.vue`),
            })
          }
        })
        router.addRoute(newRoute)
        /* newRoutes.push({
          path: '/' + menus[key].name,
          name: menus[key].name,
          component: () => import('@/views/home/Home.vue'),
          children: [],
        })
        menus[key]!.children!.forEach((item) => {
          if (!item.hidden) {
            newRoutes[newRoutes.length - 1].children?.push({
              path: item.name,
              name: item.name,
              component: () => import(`@/views/${menus[key].name}/${item.name.charAt(0).toUpperCase() + item.name.slice(1)}.vue`),
            })
          }
        }) */
      }
      // console.log(to, to.path, to.fullPath)
      // console.log(newRoutes)
      return next(to.fullPath)
    }
    // else {
    //   //网络出问题，不清除 token 下一次还会进入 if
    //   localStorage.removeItem('token')
    //   return next('/login')
    // }
  } else if (token && to.path == '/login' && userStore.menus.length !== 0) {
    ElMessage.warning('请先退出登录！')
    return next(from)
  } else if (!token && to.path != '/login') {
    ElMessage.warning('请先登录！')
    return next('/login')
  } else {
    return next()
  }
})

export const initRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
